@csrf_exempt
def all_products(request):
    if request.method == 'GET':
        try:
            # 获取分页参数
            page = int(request.GET.get('page', 1))
            page_size = int(request.GET.get('page_size', 10))
            # 添加: 获取搜索关键字参数
            search = request.GET.get('query', '')
            # 添加: 获取分类参数
            category = request.GET.get('category', '')

            # 获取所有商品
            products = Product.objects.all()
            # 添加: 根据搜索关键字过滤商品
            if search:
                products = products.filter(name__icontains=search)
            # 添加: 根据分类名称过滤商品
            if category:
                products = products.filter(category__name__icontains=category)

            # 计算分页数据
            start = (page - 1) * page_size
            end = start + page_size
            paginated_products = products[start:end]

            # 转换为列表
            products_list = list(paginated_products.values('id', 'name', 'description', 'price', 'stock', 'category__name', 'image', 'status', 'created_at', 'updated_at'))

            return JsonResponse({
                'code': 200,
                'message': '获取成功',
                'data': products_list,
                'total': products.count(),
                'page': page,
                'page_size': page_size
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'获取商品失败: {str(e)}'
            })
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })